﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZYSocket.ClientA;
using CSM.Protocol;
using CSM.System.User;

namespace CSMClient
{
	public partial class FormMain : Form
	{
		private UserToken token = null;
		private UserInfo userInfo = null;

		public FormMain()
		{
			if (SocketManager.client.ConnectionTo("127.0.0.1", 3824)) //连接到服务器
			{
				FormLogin login = new FormLogin();

				login.ShowDialog();
				if (!login.isLogin) //如果登入界面关闭那么检查是否登入成功如果没有登入成功 则关闭程序
				{
					throw new Exception("用户登陆失败");
				}

				SocketManager.Disconnection += new ExceptionDisconnection(client_Disconnection); //注册断开事件
				SocketManager.DataInput += new DataOn(client_DataOn);//注册数据包输入事件
				InitializeComponent();
			}
			else
			{
				MessageBox.Show("无法连接服务器"); //无法连接 提示 并关闭
				throw new Exception("无法连接服务器");
			}
		}

		void client_DataOn(byte[] data)
		{
			ProtocolBase[] p = Protocol.Parser(data, ref token);
			if (p != null)
			{
				foreach (ProtocolBase item in p)
				{
					switch (item.Type)
					{
						case ProtocolWord.LoginResponse:
							break;
						default:
							break;
					}
				}
			}
		}

		void client_Disconnection(string message)
		{
			MessageBox.Show(message); //断开显示消息 并关闭窗口
			this.Close();
		}

		private void FormMain_Shown(object sender, EventArgs e)
		{
			FormDownload down = new FormDownload();

			if (down.ShowDialog() == DialogResult.Cancel)
			{
				this.BeginInvoke(new EventHandler((o, ps) => Close()));  //关闭窗口
			}
		}
	}
}
